package main

import (
	"fmt"
	"github.com/panjf2000/gnet/v2"
	"github.com/panjf2000/gnet/v2/pkg/logging"
	"time"
)

type testServer struct {
	serverName string
	gnet.BuiltinEventEngine
	eng       gnet.Engine
	addr      string
	multicore bool
}

func (s *testServer) OnBoot(eng gnet.Engine) gnet.Action {
	s.eng = eng
	s.serverName = "server1"
	logging.Infof("echo server with multi-core=%t is listening on %s\n", s.multicore, s.addr)
	return gnet.None
}

func (s *testServer) OnTraffic(c gnet.Conn) gnet.Action {
	buf, _ := c.Next(-1)
	fmt.Println("Received Message:", string(buf))
	time.Sleep(time.Second * 1)
	resp := s.serverName + " echo: " + string(buf)
	c.Write([]byte(resp))
	return gnet.None
}

func main() {
	port := 9000
	test := &testServer{addr: fmt.Sprintf("tcp://:%d", port), multicore: false}
	err := gnet.Run(test, test.addr, gnet.WithMulticore(test.multicore))
	logging.Infof("server exits with error: %v", err)
}
